package sync.demo01;

/**
 * @author lwj
 * @date 2025-03-12
 * @vesion 1.0.0
 */
public class MyRunnable implements Runnable{
    /**
     * 电影票
     */
    private int ticket = 50;
    // 字符串常量
    // private String lock = "";
    // private static Object lock = new Object();
    // private Class<?> lock = Object.class;

    @Override
    public void run() {

        // 注意：锁的临界区范围 - 否则别的线程没有机会进来
        while(true) {
            synchronized (this){
                if (ticket <= 0) {
                    break;
                }

                try {
                    Thread.sleep(10);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }

                String name = Thread.currentThread().getName();
                System.out.println(name + "出售了第" + ticket-- + "张票");
            }
        }
    }
}
